<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/9/23
 * Time: 10:41
 */
namespace App\Http\Controllers\admin_system;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Module\EntManageuser;
use App\Module\EntBookType;
use App\Module\EntBookInfo;
use App\Module\EntBookImg;
use Storage;
use Cookie;
use DB;
use Validator;
use Redirect;
use Session;
use App\Models\V1\BookModel;


class BookController extends Controller
{
    protected $data = [
        'title' => '网站后台管理中心',
        'keywords' => '网站后台管理中心',
        'description' => '网站后台管理中心'
    ];

    private $form_rules = [
        'txtTypeName' => 'required',
        'txtSort' => 'required'
    ];
    private $form_msg = [
        'txtTypeName.required' => '分类不能为空！',
        'txtSort.required' => '排序不能为空！',
    ];

    /*
     * 显示书籍分类列表
     *
     * */
    public function book_type($keyword = '')
    {
        if ($keyword != '') {
            $BookTypes = DB::table('VW_BookType')->select('TypeID', 'TypeName', 'SortNumber', 'IsShow', 'MasterID', 'DeleteMark', 'ReleaseDate', 'RealName')
                ->where('DeleteMark', '1')
                ->where('TypeName', 'like', '%' . $keyword . '%')
                ->orderBy('SortNumber', 'desc')
                ->paginate(20);
            //search
        } else {
            $BookTypes = DB::table('VW_BookType')->select('TypeID', 'TypeName', 'SortNumber', 'IsShow', 'MasterID', 'DeleteMark', 'ReleaseDate', 'RealName')
                ->where('DeleteMark', '1')
                ->orderBy('SortNumber', 'desc')
                ->paginate(20);
        }
        return view('admin_system/books/type', [
            'BookTypes' => $BookTypes,
            'keyword' => $keyword
        ]);
    }

    /*
     * 创建分类显示页面
     * */
    public function type_create()
    {
        return view('admin_system.books.typeAdd');
    }

    /*
     * 添加书籍分类
     * */
    public function type_store(Request $request)
    {
        $AName = Session::get('AName');
        $AKey = Session::get('AKey');
        $data = $this->data;
        if ($AKey != '' && $AName != '') {
            $entManageuser = EntManageuser::select('UserID')->where('UserName', $AName)
                ->where('UserPwd', md5($AKey))
                ->where('DeleteMark', 1)
                ->first();
        }
        if ($entManageuser) {
            $validator = Validator::make($request->all(), $this->form_rules, $this->form_msg);
            if ($validator->fails()) {
                return redirect::back()->withInput()->withErrors($validator);
            }
            $AName = $request->cookie('AName');
            $AKey = $request->cookie('AKey');
            $entBookType = new EntBookType();
            $entBookType->TypeName = trim($request->get('txtTypeName'));
            $entBookType->ParentID = 0;
            $entBookType->SortNumber = trim($request->get('txtSort'));
            $entBookType->IsShow = $request->get('RadIsShow');
            $entBookType->MasterID = $entManageuser->UserID;
            $entBookType->DeleteMark = 1;
            $entBookType->ReleaseDate = date('Y-m-d H:i:s', time());
            $entBookType->AddDate = date('Y-m-d H:i:s', time());
            $entBookType->save();
            $result = '';
            if ($entBookType) {
                $result = '分类信息添加成功！';
            } else {
                $result = '分类信息添加失败！';
            }
            return redirect::back()->withInput()->withErrors($result);
        }

    }

    /*
     * 修改书籍分类页面
     * */
    public function type_edit($id)
    {
        try {
            $entBookType = EntBookType::findOrFail($id);
        } catch (ModelNotFoundException $e) {
            throw new NotFoundHttpException();
        }
        return view('admin_system.books.typeEdit', ['entBookType' => $entBookType]);
    }

    /*
     * 修改书籍分类操作
     * */
    public function type_update(Request $request, $id)
    {
        $validator = Validator::make($request->all(), $this->form_rules, $this->form_msg);
        if ($validator->fails()) {
            return redirect::back()->withInput()->withErrors($validator);
        }
        $entBookType = EntBookType::find($id);
        $entBookType->TypeName = trim($request->get('txtTypeName'));
        $entBookType->SortNumber = trim($request->get('txtSort'));
        $entBookType->IsShow = $request->get('RadIsShow');
        $entBookType->ReleaseDate = date('Y-m-d H:i:s', time());
        $entBookType->save();
        $result = '';
        if ($entBookType) {
            $result = '分类信息修改成功！';
        } else {
            $result = '分类信息修改失败！';
        }
        return redirect::back()->withInput()->withErrors($result);
    }

    /*
     * 删除书籍分类
     * */
    public function type_delete(Request $request)
    {
        $result = '';
        try {
            if ($request->ajax()) {
                $IDList = $request->json('IDList');
                if (is_numeric($IDList)) {
                    EntBookType::where('TypeID', $IDList)->update([
                        'DeleteMark' => '0'
                    ]);
                    $result = 'ok';
                } else {
                    EntBookType::whereIn('TypeID', explode(',', $IDList))->update([
                        'DeleteMark' => '0'
                    ]);
                    $result = 'ok';
                }
            }
        } catch (Exception $e) {
            $result = 'no';
        }
        return $result;
    }


    /*================ 书籍列表end ===================*/


    /*
     * 显示书籍列表
     * */
    public function index(Request $request)
    {
        $keyword    = $request->input('KeyWords');
        $type       = $request->input('type',0);
        $isFree     = $request->input('isFree',2);


        $books  = DB::table('bookinfo as a')
            ->leftJoin('booktype as b','b.TypeID','=','a.TypeID')
            ->select('a.*','b.TypeName')
            ->where('a.DeleteMark',1)


            ->where(function($db)use($keyword,$type,$isFree){

                $keyword && $db->where('a.BookTitle','like',"%{$keyword}%");
                $type> 0 && $db->where('a.TypeID',$type);
                $isFree<2&& $db->where('a.IsGratis',$isFree);
            })

            ->orderBy('a.publish_date','desc')
            ->paginate(20);

        $bookTypes  = (new BookModel())->get_book_types();

        $data   = [
            'BookInfo'  => $books,
            'bookTypes' => $bookTypes,
            'paras'     => ['keyword'=>$keyword,'type'=>$type,'isFree'=>$isFree]
        ];
        return view('admin_system.books.index', $data);
    }



    protected function get_subtraction()
    {
        $t1 = microtime(true) * 10000;
        return $t1;
    }



    /*
     * 编辑书籍显示
     * */
    public function bookEdit(Request $request)
    {
        //分类
        $bookTypes  = (new BookModel())->get_book_types();

        $bookId     = $request->input('bookId',0);
        $tags       = DB::table('book_tags')->get();

        //书籍详细
        if($bookId > 0)
        {
            $bookInfo = EntBookInfo::findOrFail($request->bookId);
            //$bookInfo->tags = explode(',',$bookInfo->tags);
            //PPT
            $bookImg = EntBookImg::select('BookImgID', 'FilePath1')
                ->where('BookID', $request->bookId)
                ->orderBy('SortNumber', 'asc')
                ->get();

        }else {

            $bookImg  = [];
            $bookInfo = new \stdClass();
            $bookInfo->BookID       = 0;
            $bookInfo->video_type   = "";
            $bookInfo->TypeID       = "";
            $bookInfo->BookTitle    = "";
            $bookInfo->author       = "";
            $bookInfo->ReadNumber   = "";
            $bookInfo->publish_date = date('Y-m-d',time());
            $bookInfo->BookDesc     = "";
            $bookInfo->tags         = "";
            $bookInfo->mp4          = "";
            $bookInfo->mp3          = "";
            $bookInfo->article      = "";
            $bookInfo->IsGratis     = 0;
            $bookInfo->IsShow       = 1;
            $bookInfo->SortNumber   = 0;

            $bookInfo->book_img     = "";
            $bookInfo->bg_img       = "";
            $bookInfo->ppt          = "";

        }

        $data   = [
            'entBookInfo'   => $bookInfo,
            'SelectType'    => $bookTypes,
            'entBookImg'    => $bookImg,
            'tags'          => $tags
        ];
        return view('admin_system.books.edit', $data);
    }

    /*
     * 编辑书籍更新
     * */
    public function editAction(Request $request)
    {
        $AName  = Session::get('AName');
        $AKey   = Session::get('AKey');
        $bookId = $request->input('bookId',0);
        $time   = date_time();
        if ($AKey != '' && $AName != '')
        {
            $entManageuser = EntManageuser::select('UserID')
                ->where('UserName', $AName)
                ->where('UserPwd', md5($AKey))
                ->where('DeleteMark', 1)
                ->first();

        }

        if($bookId > 0)
        {
            $entBookInfo = EntBookInfo::find($bookId);
        }else{
            $entBookInfo = new EntBookInfo();
            $entBookInfo->AddDate = $time;
        }


        $entBookInfo->TypeID        = $request->get('TypeIDSelect');
        $entBookInfo->BookTitle     = trim($request->get('txtBookTitle'));
        $entBookInfo->BookDesc      = trim($request->get('txtBookDesc'));
        $entBookInfo->TypeID        = $request->get('TypeIDSelect');
        $entBookInfo->ReadNumber    = $request->get('txtReadNumber');
        $entBookInfo->publish_date  = $request->get('txtPublishDate');
        $entBookInfo->ppt           = $request->get('ppt');
        $entBookInfo->author        = $request->get('author');
        $entBookInfo->video_type    = $request->get('video_type');
        $entBookInfo->book_img      = $request->get('File_bookimg');
        $entBookInfo->bg_img        = $request->get('bg_img');
        $entBookInfo->mp4           = trim($request->get('mp4'));
        $entBookInfo->mp3           = trim($request->get('mp3'));
        $entBookInfo->SortNumber    = $request->get('txtSortNumber');
        $entBookInfo->MasterID      = $entManageuser->UserID;
        $entBookInfo->IsGratis      = $request->get('RadIsGratis');
        $entBookInfo->IsShow        = $request->get('RadIsShow');
        $entBookInfo->ReleaseDate   = $time;

        $entBookInfo->tags          = $request->input('tags','');//implode(',',$request->get('tags',[]));
        $entBookInfo->article       = $request->input('article','');
        $entBookInfo->save();

        if ($entBookInfo)
        {
            EntBookImg::where('BookID', $request->get('hiImgID'))->update(['BookID' => $entBookInfo->BookID]);
            $result = '书籍修改成功！';
            table_log('bookinfo',$bookId,$request->all());
        } else {
            $result = '书籍修改失败！';
        }
        return apiData()->notice($result);
    }


    public function tags(Request $request)
    {
        $method = $request->method();
        $id     = $request->input('id',0);
        $tag    = $request->input('tag','');

        if($id > 0 )
        {
            DB::table('book_tags')->where('id',$id)->delete();
        }

        if($method == 'POST')
        {
            $hasTag = DB::table('book_tags')->where('tag',$tag)->first();
            if(!$hasTag)
            {
                DB::table('book_tags')->insert(['tag'=>$tag]);
            }
        }
        $tags   = DB::table('book_tags')->get();
        return view('/admin_system/books/tags',['tags'=>$tags]);
    }


    /*
     * 删除书籍
     * */
    public function indexdelete(Request $request)
    {
        $result = '';
        try {
            if ($request->ajax()) {
                $IDList = $request->json('IDList');
                if (is_numeric($IDList)) {
                    EntBookInfo::where('BookID', $IDList)->update([
                        'DeleteMark' => '0'
                    ]);
                    $result = 'ok';
                } else {
                    EntBookInfo::whereIn('BookID', explode(',', $IDList))->update([
                        'DeleteMark' => '0'
                    ]);
                    $result = 'ok';
                }
            }
        } catch (Exception $e) {
            $result = 'no';
        }
        return $result;
    }


    /*
     * 添加PPT
     * */
    public function storePPT(Request $request)
    {
        $result = '';
        try {
            if ($request->ajax()) {
                $id = $request->json('id');
                $url = $request->json('url');
                $number = $request->json('number');
                $entBookImg = new EntBookImg();
                $entBookImg->BookID = $id;
                $entBookImg->FilePath1 = $url;
                $entBookImg->SortNumber = $number;
                $entBookImg->AddDate = date('Y-m-d H:i:s', time());
                $entBookImg->save();
                if ($entBookImg) {
                    $result = $entBookImg->BookImgID;
                } else {
                    $result = 'no';
                }
            }
        } catch (Exception $e) {
            $result = 'no';
        }
        return $result;
    }

    /*
     * 删除文件
     * */
    public function delFile(Request $request)
    {
        $url    = trim($request->json('url'),"/");
        $url    = public_path($url);
        unlink($url);
        return "删除成功！";
    }


    /*
     * 删除PPT
     * */
    public function pptFileDelete(Request $request)
    {
        $result = '';
        try {
            if ($request->ajax()) {
                $IDList = $request->json('IDList');
                if (is_numeric($IDList)) {
                    $entBookImg = EntBookImg::destroy($IDList);
                    if (count($entBookImg) > 0) {
                        $result = 'ok';
                    } else {
                        $result = 'no';
                    }
                }
            }
        } catch (Exception $e) {
            $result = 'no';
        }
        return $result;
    }

}